<?php

/**
 * dispatchOrder actions.
 *
 * @package    WacStorehouse
 * @subpackage dispatchOrder
 * @author     JianBinBi
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class dispatchOrderActions extends WacCommonActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('default', 'module');
  }
  
  /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeNewListIndex(sfWebRequest $request)
  {
      ;
  }

  /*
   * @return hash list data array
   * @keyField - key field
   * @valField - value field
   * @page     - at pager
   * @rows=20  - rows per pager
   *    *
   */
  protected function getHashList($keyField, $valField, $page=1, $rows=20)
  {
      $resultSet = array();
      $arrParam = array();

      $request = $this->getRequest();
      if($request->hasParameter("status"))
      {
          $arrParam['andWhere'][] = "status=".StaticWacFormStatus::getId($request->getParameter("status"));
      }

      if($request->hasParameter("type"))
      {
          $arrParam['andWhere'][] = "type=".$request->getParameter("type");
      }

      if($request->hasParameter(JqFlexboxDataHelper::$querySting) && $request->getParameter(JqFlexboxDataHelper::$querySting)!="")
      {
          $arrParam['andWhere'][] = "{$valField} like '".$request->getParameter(JqFlexboxDataHelper::$querySting)."%'";
      }

      $arrParam['orderBy'] = "t1.id asc";

      $listItems = $this->mainModuleTable->getCustomList($arrParam, $page, $rows, true);

      if(count($listItems)>0)
      {
          foreach($listItems as $listItem)
          {
              $tmpArr = array();
              $tmpArr = array("key"=>$listItem[$keyField], "value"=>$listItem[$valField]);
              $resultSet[] = $tmpArr;
          }
      }

      return $resultSet;
  }

  /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeAuditedListIndex(sfWebRequest $request)
  {
      ;
  }

  public function executeDyeNewListIndex(sfWebRequest $request)
  {
      $request->setParameter("type", WacBizOrderType::$type["dye"]);
      $this->forward('dispatchOrder', 'NewListIndex');
  }

  public function executeDyeAuditedListIndex(sfWebRequest $request)
  {
      $request->setParameter("type", WacBizOrderType::$type["dye"]);
      $this->forward('dispatchOrder', 'AuditedListIndex');
  }

  public function executeWeaveNewListIndex(sfWebRequest $request)
  {
      $request->setParameter("type", WacBizOrderType::$type["weave"]);
      $this->forward('dispatchOrder', 'NewListIndex');
  }

  public function executeWeaveAuditedListIndex(sfWebRequest $request)
  {
      $request->setParameter("type", WacBizOrderType::$type["weave"]);
      $this->forward('dispatchOrder', 'AuditedListIndex');
  }

  public function executeCleanUpNewListIndex(sfWebRequest $request)
  {
      $request->setParameter("type", WacBizOrderType::$type["cleanUp"]);
      $this->forward('dispatchOrder', 'NewListIndex');
  }

  public function executeCleanUpAuditedListIndex(sfWebRequest $request)
  {
      $request->setParameter("type", WacBizOrderType::$type["cleanUp"]);
      $this->forward('dispatchOrder', 'AuditedListIndex');
  }
  
  public function executeFinalClothNewListIndex(sfWebRequest $request)
  {
      $request->setParameter("type", WacBizOrderType::$type["finalCloth"]);
      $this->forward('dispatchOrder', 'NewListIndex');
  }

  public function executeFinalClothAuditedListIndex(sfWebRequest $request)
  {
      $request->setParameter("type", WacBizOrderType::$type["finalCloth"]);
      $this->forward('dispatchOrder', 'AuditedListIndex');
  }


  /*
   * @return list data array
   */
  public function executeGetFormData(sfWebRequest $request)
  {
      
      $resultSet = JsCommonData::getCommonDatum();
      $resultSet['info'] = JsCommonData::getSuccessDatum();

      // default data setting
      $resultSet['items']['unit'] = Doctrine::getTable(WacTable::$unit)->getCodeNameHash();

      // editing data setting
      if($request->hasParameter("id") && $request->getParameter("id")!="0")
      {
          $objOrder = Doctrine::getTable(WacTable::$dispatchOrder)->findOneBy("id", $request->getParameter("id"));
          $limitGoodsCategorys = WacDispatchOrder::getLimitGoodsCategorys($objOrder->getType());
          $resultSet['items']['stock_goods_items'] = $objOrder->getWacSupplier()->getStockGoodsListWithDetail(array(), 1, 10, $limitGoodsCategorys);
          $resultSet['items']['target_items'] = $objOrder->getSubItemsWithDetail();
      }
      else{
          $resultSet['items']['stock_goods_items'] = array();
          $resultSet['items']['target_items'] = array();
      }

//      $resultSet['items']['default']['currency_code_name'] = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$currency);
      $resultSet['items']['default']['unit_code']    = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::getCodeByBizOrderType($request->getParameter("type")));

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  public function executeGetList(sfWebRequest $request)
  {
      $jqGridDataHelper = JqGridDataHelper::getInstance();

        $arrParams = array();
        if($jqGridDataHelper->loadComplexQuery($request)) {

            if($request->hasParameter(JqGridDataHelper::$KEY_SEARCH_FIELD) && $request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER)!="") {
                $arrParams['andWhere'] = array(
                        $jqGridDataHelper->getCondMapStr($request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER), "t1.".$request->getParameter(JqGridDataHelper::$KEY_SEARCH_FIELD), $request->getParameter(JqGridDataHelper::$KEY_SEARCH_STRING))
                );
            }

            if($request->hasParameter("type_code")) {
                $arrParams['andWhere'][] = "t1.type=".$request->getParameter("type_code");
            }

            if($request->hasParameter("status")) {
                $arrParams['andWhere'][] = "t1.status=".StaticWacFormStatus::getId($this->getRequest()->getParameter("status"));
            }

            if($request->hasParameter(JqGridDataHelper::$KEY_SIDX)) {
                switch($request->getParameter(JqGridDataHelper::$KEY_SIDX)) {
                    case "production_order_code":
                        $arrParams['orderBy'] = "wpo.code ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "supplier_name":
                        $arrParams['orderBy'] = "ws.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "target_name":
                        $arrParams['orderBy'] = "wt.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "status_name":
                        $arrParams['orderBy'] = "t1.status ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "maker_name":
                        $arrParams['orderBy'] = "wm.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "auditor_name":
                        $arrParams['orderBy'] = "wa.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    default:
                        $arrParams['orderBy'] = "t1.".$request->getParameter(JqGridDataHelper::$KEY_SIDX)." ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                }
            }

            $resultSet = $this->mainModuleTable->getCustomList($arrParams, $request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false);
        }
        else {
            if($request->hasParameter("status")) {
                $arrParams['andWhere'][] = "status=".StaticWacFormStatus::getId($this->getRequest()->getParameter("status"));
            }
            if($request->hasParameter("type_code")) {
                $arrParams['andWhere'][] = "type=".$request->getParameter("type_code");
            }
            $resultSet = $this->mainModuleTable->getCommonList($request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false, $arrParams);
        }

        $filterResultSet = $this->filterList($resultSet);

        $pager = $this->mainModuleTable->getPager();
        $filterResultSet = $jqGridDataHelper->convert($filterResultSet, $pager, JsCommonData::getSuccessDatum());

        return OutputHelper::getInstance()->outputJsonOrTextFormat($filterResultSet, $this);
      
  }

  /*
   * override filter list
   */
  public function filterList($listObjs)
  {
      $filterArr = array();
      if(count($listObjs) > 0)
      {
          foreach($listObjs as $listObj)
          {
              $tmpArr = $listObj->toArray();
              $tmpArr['production_order_code']        = $listObj->getWacProductionOrder()->getCode();
              $tmpArr['goods_amount_unit_code_name']  = $listObj->getWacGoodsAmountUnitCode()->getName();
              $tmpArr['supplier_name']                = $listObj->getWacSupplier()->getName();
              $tmpArr['target_name']                  = $listObj->getWacTarget()->getName();

              $formatDate = new DateTime($listObj->getStartDate());
              $tmpArr['start_date']                   = $formatDate->format("Y-m-d");

              $formatDate = new DateTime($listObj->getDeliveryDate());
              $tmpArr['delivery_date']                = $formatDate->format("Y-m-d");

              $tmpArr['status_name']                  = StaticWacFormStatus::getCaptionById($listObj->getStatus());

              $filterArr[] = $tmpArr;
          }
      }

      return $filterArr;
  }

  /*
   * @return inspect result
   */
  public function inspectDataValidation(sfWebRequest $request, $params=array())
  {
      $result    = JsCommonData::getSuccessDatum();
      $reqParams = $request->getParameterHolder()->getAll();


      $exceptId = isset($reqParams['id']) ? $reqParams['id'] : 0;
      if($this->mainModuleTable->isExistedCode($reqParams['code'], $exceptId))
      {
         $result = JsCommonData::getErrorDatum(WacErrorCode::getInfo(WacErrorCode::$duplicatedName, $reqParams['code']), WacErrorCode::$duplicatedName);
         return $result;
      }

      if(empty($reqParams['production_order_id']) || !Doctrine::getTable(WacTable::$productionOrder)->isExistedId($reqParams['production_order_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_production_order"),  WacErrorCode::$logicError
                  );
         return $result;
      }

      if(empty($reqParams['supplier_id']) || !Doctrine::getTable(WacTable::$factory)->isExistedId($reqParams['supplier_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_supplier"),  WacErrorCode::$logicError
                  );
         return $result;
      }

      if(empty($reqParams['target_id']) || !Doctrine::getTable(WacTable::$factory)->isExistedId($reqParams['target_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_target"),  WacErrorCode::$logicError
                  );
         return $result;
      }

      return $result;
  }

    /*
   * @return list data array
   */
  public function executeAdd(sfWebRequest $request)
  {
      $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
      $resultSet     = JsCommonData::getCommonDatum();
      $inspectResult = $this->inspectDataValidation($request);

      if($inspectResult['status'] == WacOperationStatus::$Error)
      {
          $resultSet['info'] = $inspectResult;
      }
      else
      {
          $objProductionOrder = Doctrine::getTable(WacTable::$productionOrder)->findOneBy('id', $reqParams['production_order_id']);
          $targetItem        = $this->mainModuleTable->create();

          if(count($reqParams)>0) {
//              $targetItem->set($reqParams['']);
              $targetItem->setMakerId($this->getUser()->getGuardUser()->getId());
              $targetItem->setCurrencyCode($objProductionOrder->getCurrencyCode());

              if(isset($reqParams['code']))                {$targetItem->setCode($reqParams['code']);}
              if(isset($reqParams['type']))                {$targetItem->setType(WacBizOrderType::$type[$reqParams['type']]["code"]);}
              if(isset($reqParams['production_order_id'])) {$targetItem->setProductionOrderId($reqParams['production_order_id']);}
              if(isset($reqParams['supplier_id']))         {$targetItem->setSupplierId($reqParams['supplier_id']);}
              if(isset($reqParams['target_id']))           {$targetItem->setTargetId($reqParams['target_id']);}
//              if(isset($reqParams['start_date']))          {$targetItem->setStartDate($reqParams['start_date']);}
              if(isset($reqParams['delivery_date']))       {$targetItem->setDeliveryDate($reqParams['delivery_date']);}
              if(isset($reqParams['goods_amount_unit_code'])) {$targetItem->setGoodsAmountUnitCode($reqParams['goods_amount_unit_code']);}
              if(isset($reqParams['memo']))                {$targetItem->setMemo($reqParams['memo']);}

              $targetItem->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$init));
              $targetItem->save();

              if(count($reqParams['target_goods'])>0)
              {
                  $goodsAmount = 0;
                  $costAmount = 0;
                  foreach($reqParams['target_goods'] as $k=>$v)
                  {
                      $goodsId = substr($k, 3);
                      $objSrcGoodsItem = Doctrine::getTable(WacTable::$factoryGoodsItem)->findOneByFactoryAndGoods($reqParams['supplier_id'], $goodsId);
                      $objGoods = $objSrcGoodsItem->getWacGoods();
                      
                      $objSubItem = Doctrine::getTable(WacTable::$dispatchOrderItem)->create();
                      $objSubItem->setProductionOrderId($objProductionOrder->getId());
                      $objSubItem->setSrcProductionOrderId($objProductionOrder->getId());
                      $objSubItem->setDispatchOrderId($targetItem->getId());
                      $objSubItem->setGoodsId($objGoods->getId());
                      $objSubItem->setGoodsCategoryId($objGoods->getGoodsCategoryId());
                      $objSubItem->setGoodsNumber($v);
                      $objSubItem->setGoodsNumberUnitCode($targetItem->getGoodsAmountUnitCode());
                      $objSubItem->setGoodsNumberUnitPrice($objSrcGoodsItem->getGoodsNumberUnitPrice());
                      $objSubItem->setCost($v * $objSrcGoodsItem->getGoodsNumberUnitPrice());
                      $objSubItem->setCurrencyCode($objSrcGoodsItem->getCurrencyCode());
                      $objSubItem->save();

                      $goodsAmount+=$objSubItem->getGoodsNumber();
                      $costAmount+=$objSubItem->getCost();
                  }
                  $targetItem->setGoodsAmount($goodsAmount);
                  $targetItem->setCostAmount($goodsAmount);
                  $targetItem->save();
              }

              $this->afterAdd($request, $targetItem);

              // process production order
              $objWorkflowItem = Doctrine::getTable(WacTable::$workflowItem)->findOneBy('code', StaticWacWorkFlow::$wfDispatch[$reqParams["type"]]);
              $objProductionOrder->setCurrentWorkflowItemId($objWorkflowItem->getId());
//              $objProductionOrder->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$processing));
              $objProductionOrder->save();
          }

          $resultSet['items'][0] = $targetItem->toArray();
          $resultSet['info']     = JsCommonData::getSuccessDatum(
                                       Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_add_succ")
                                   );
      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return list data array
   */
  public function executeEdit(sfWebRequest $request)
  {
      // forward to 404 if no id
      $this->forward404Unless($request->hasParameter('id'));

      $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
      $resultSet     = JsCommonData::getCommonDatum();
      $inspectResult = $this->inspectDataValidation($request);

      if($inspectResult['status'] == WacOperationStatus::$Error)
      {
          $resultSet['info'] = $inspectResult;
      }
      else
      {
          $targetItem = $this->mainModuleTable->findOneById($request->getParameter('id'));

          if(count($reqParams)>0) {
              if($targetItem->getSupplierId()!=$reqParams['supplier_id']){
                  $targetItem->deleteSubItems();
              }

              if(count($reqParams['target_goods'])>0)
              {
                  $goodsIds =  array();
                  $goodsAmount = 0;
                  $costAmount = 0;
                  foreach($reqParams['target_goods'] as $k=>$v)
                  {
                      $goodsId = substr($k, 3);
                      $goodsIds[] = $goodsId;
                      $objSubItem = Doctrine::getTable(WacTable::$dispatchOrderItem)->findOneByOrderAndGoods($targetItem->getId(), $goodsId);
                      if($objSubItem){  // existed goods
                          $objSubItem->setGoodsNumber($v);
                      }
                      else{
                          $objProductionOrder = $targetItem->getWacProductionOrder();
                          $objSrcGoodsItem = Doctrine::getTable(WacTable::$factoryGoodsItem)->findOneByFactoryAndGoods($reqParams['supplier_id'], $goodsId);
                          $objGoods = Doctrine::getTable(WacTable::$goods)->findOneBy("id", $goodsId);

                          $objSubItem = Doctrine::getTable(WacTable::$dispatchOrderItem)->create();
                          $objSubItem->setProductionOrderId($objProductionOrder->getId());
                          $objSubItem->setSrcProductionOrderId($objProductionOrder->getId());
                          $objSubItem->setDispatchOrderId($targetItem->getId());
                          $objSubItem->setGoodsId($objGoods->getId());
                          $objSubItem->setGoodsCategoryId($objGoods->getGoodsCategoryId());
                          $objSubItem->setGoodsNumber($v);
                          $objSubItem->setGoodsNumberUnitCode($targetItem->getGoodsAmountUnitCode());
                          $objSubItem->setGoodsNumberUnitPrice($objSrcGoodsItem->getGoodsNumberUnitPrice());
                          $objSubItem->setProcessingFee($v * $objSrcGoodsItem->getGoodsNumberUnitPrice());
                          $objSubItem->setCost($v * $objSrcGoodsItem->getGoodsNumberUnitPrice());
                          $objSubItem->setCurrencyCode($objSrcGoodsItem->getCurrencyCode());
                      }
                      $objSubItem->save();

                      $goodsAmount+=$objSubItem->getGoodsNumber();
                      $costAmount+=$objSubItem->getCost();
                  }

                  $objSubItems = $targetItem->getWacSubItems();
                  if($objSubItems->count()>0)
                  {
                      foreach($objSubItems as $objSubItem)
                      {
                          if(!in_array($objSubItem->getGoodsId(), $goodsIds))
                          {
                              $objSubItem->delete();
                          }
                      }
                  }

                  $targetItem->setGoodsAmount($goodsAmount);
                  $targetItem->setCostAmount($goodsAmount);
                  $targetItem->save();
              }

              if(isset($reqParams['code']))                {$targetItem->setCode($reqParams['code']);}
              if(isset($reqParams['production_order_id'])) {$targetItem->setProductionOrderId($reqParams['production_order_id']);}
              if(isset($reqParams['supplier_id']))         {$targetItem->setSupplierId($reqParams['supplier_id']);}
              if(isset($reqParams['target_id']))           {$targetItem->setTargetId($reqParams['target_id']);}
//              if(isset($reqParams['start_date']))          {$targetItem->setStartDate($reqParams['start_date']);}
              if(isset($reqParams['delivery_date']))       {$targetItem->setDeliveryDate($reqParams['delivery_date']);}
              if(isset($reqParams['goods_amount_unit_code'])) {$targetItem->setGoodsAmountUnitCode($reqParams['goods_amount_unit_code']);}
              if(isset($reqParams['memo']))                {$targetItem->setMemo($reqParams['memo']);}

              $targetItem->save();
              $this->afterEdit($request, $targetItem);
          }

          $resultSet['items'][0] = $targetItem->toArray();
          $resultSet['info']     = JsCommonData::getSuccessDatum(
                                       Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_edit_succ")
                                   );
      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return inspect result
  */
  protected function auditValidation(sfWebRequest $request, $objDispatchOrder, $params=array()) {
      $result    = JsCommonData::getSuccessDatum();
      $reqParams = $request->getParameterHolder()->getAll();

      if($objDispatchOrder->getStatus() != StaticWacFormStatus::getId(StaticWacFormStatus::$init)) {
          $result = JsCommonData::getErrorDatum(
                  Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_status"),  WacErrorCode::$logicError
          );
          return $result;
      }

      $items = $objDispatchOrder->getWacSubItems();
      if($items->count()==0) {
          $result = JsCommonData::getErrorDatum(
                  Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_zero_item"),  WacErrorCode::$logicError
          );
          return $result;

      }

      return $result;
  }

  /*
     * @return list data array
  */
  public function executeAudit(sfWebRequest $request) {
      // forward to 404 if no id
      $this->forward404Unless($request->hasParameter('order_id'));

      $resultSet = JsCommonData::getCommonDatum();

      $objDispatchOrder = Doctrine::getTable(WacTable::$dispatchOrder)->findOneBy('id', $request->getParameter('order_id'));
      $validationResult = $this->auditValidation($request, $objDispatchOrder);

      if($validationResult['status'] == WacOperationStatus::$Error) {
          $resultSet['info'] = $validationResult;
      }
      else {
          try {
              $objSupplier = $objDispatchOrder->getWacSupplier();
              $opResultData = $objSupplier->getMinusOrderItemConsumeGoods($objDispatchOrder->getWacSubItems());
              if($opResultData["error"]) {
                  $errorMsgPtn = Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_goods_number_insufficient_in_factory");
                  $errorMsg = MessageHelper::getInstance()->getMsgOfMinusOrderItemConsumeGoods($opResultData, $errorMsgPtn);
                  throw new WacAppException($errorMsg, WacErrorCode::$logicError);
              }
              else {
//                  $objSupplier->setMinusOrderItemConsumeGoods($opResultData);
                  $objSupplier->decreaseGoods($objDispatchOrder);
              }


              $objTarget = $objDispatchOrder->getWacTarget();
              $objTarget->storeGoods($objDispatchOrder);
              $objDispatchOrder->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$audited));
              $objDispatchOrder->setAuditorId($this->getUser()->getGuardUser()->getId());
              $objDispatchOrder->setAuditorDate(format_date(time()));
              $objDispatchOrder->save();

              $resultSet['info'] = JsCommonData::getSuccessDatum(
                      Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_audit_succ")
              );

              $this->afterAudit($request, $objDispatchOrder);
          }
          catch (WacAppException $e) {		// catch application exception, and handle it
              $resultSet['info'] = JsCommonData::getErrorDatum($e->getMessage());
          }
          catch (Exception $e) {        // catch general exception
              WacAppException::handleGeneralError($e);
          }

      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
  }

}
